package com.angle.im.server.config.mq;

import com.aliyun.openservices.ons.api.Message;
import com.aliyun.openservices.ons.api.Producer;
import com.aliyun.openservices.ons.api.SendResult;
import com.angle.im.server.utils.CommonUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author zhangwei
 * @date 2018/9/29 18:36
 * @desc 阿里ons rocket mq 工具类
 */
@Component
@Slf4j
public class OnsComponent {

    @Autowired
    private Producer producer;

    private String topic = "music-cp";

    /**
     * 发送消息
     *
     * @param tag
     * @param msg
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public SendResult sendToOne(String tag, Object msg) {
        try {
            return producer.send(aliMessage(tag, msg));
        } catch (Exception e) {
            return null;
        }
    }
    /**
     * 发送消息
     *
     * @param tag
     * @param msg
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public SendResult sendToList(String tag, Object msg) {
        try {
            return producer.send(aliMessage(tag, msg));
        } catch (Exception e) {
            return null;
        }
    }


    /**
     * 构建阿里mq消息体
     *
     * @param tag 标签
     * @param msg 消息体(消息体可以为任何对象,不限于String或int等类型)
     * @return
     * @throws Exception
     */
    private Message aliMessage(String tag, Object msg) {
        byte[] serialize = CommonUtils.objToByteArr(msg);
        return new Message(topic, tag, serialize);
    }


    /**
     * 构建阿里mq消息体
     *
     * @param tag    标签
     * @param msg    消息体(消息体可以为任何对象,不限于String或int等类型)
     * @param second 延时时间,单位:秒
     * @return
     * @throws Exception
     */
    private Message aliMessage(String tag, Object msg, long second) {
        Message message = new Message(topic, tag, CommonUtils.objToByteArr(msg));
        message.setStartDeliverTime(System.currentTimeMillis() + (second * 1000));
        return message;
    }


}